package cn.edu.zsc.study.framework.security;

import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * ljx
 */
public class JwtAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        JwtLoginToken jwtLoginToken = (JwtLoginToken) authentication;

        JwtLoginToken authenticationToken = new JwtLoginToken(userDetails,jwtLoginToken.getCredentials(),userDetails.getAuthorities());
        authenticationToken.setDetails(jwtLoginToken.getDetails());
        return authenticationToken;

    }


    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtLoginToken.class.isAssignableFrom(authentication));
    }

    private  void additionalAuthenticationCheck(UserDetails userDetails,JwtLoginToken authentication)throws AuthenticationException{
        if(authentication.getCredentials() == null){
            throw  new BadCredentialsException("Bad credentials");
        }
        String presentPassword = authentication.getCredentials().toString();
        if(!passwordEncoder.matches(presentPassword,userDetails.getPassword())){
            throw new BadCredentialsException("Bad credentials");
        }
    }

    private void defaultCheck(UserDetails user){
        if(!user.isAccountNonLocked()){
            throw new LockedException("用户账号已锁");
        }
        if(!user.isEnabled()){
            throw new DisabledException("用户账号未开启");
        }
        if(!user.isAccountNonExpired()){
            throw new AccountExpiredException("用户账号已过期");
        }
    }
    public void setUserDetailsService(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }
    public void setPasswordEncoder(PasswordEncoder passwordEncoder){
        this.passwordEncoder = passwordEncoder;

    }
}
